package panda.query.scan;

import panda.query.struct.Attribute;
import panda.query.struct.Constant;
import panda.query.util.BufferInfo;
import panda.record.TableToken;
import panda.transaction.Transaction;

/**
 * 
 * @author Tian Yuan
 *
 */
public class PartitionProductScanner implements Scanner {
	private Scanner l, r = null, p;
	private TableToken tt;
	private int chunkSize, nextBlk, fileSize;
	private Transaction tx;
	
	public PartitionProductScanner(Scanner l, TableToken tt, Transaction tx) {
		this.l = l;
		this.tt = tt;
		this.tx = tx;
		fileSize = tx.getSize(tt.getFilename());
		chunkSize = BufferInfo.bestChunkSize(fileSize);
		init();
	}

	public void init() {
		nextBlk = 0;
		nextChunk();
	}
	
	public void close() {
		p.close();
	}
	
	public boolean next() {
		while (!p.next())
			if (!nextChunk())
				return false;
		return true;
	}
	
	public Constant getValue(Attribute attr) {
		return p.getValue(attr);
	}

	public boolean hasAttribute(Attribute name) {
		return p.hasAttribute(name);
	}
	
	private boolean nextChunk() {
		if (r != null) r.close();
		if (nextBlk >= fileSize) return false;
		int end = nextBlk + chunkSize - 1;
		if (end >= fileSize) end = fileSize - 1;
		r = new ChunkScanner(tt, nextBlk, end, tx);
		l.init();
		p = new ProductScanner(l, r);
		nextBlk = end + 1;
		return true;
	}
}
